package com.jack.thinking.java._22.swing.button;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

import com.utils.SwingConsole;

/**
 * 下拉菜单
 * @author wangbingwu
 *
 */
public class ComboBoxes extends JFrame{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String[] desc = {"Jack", "Jane", "Li"};
	private JTextField t = new JTextField(15);
	private JComboBox<String> c = new JComboBox<>(); // JDK1.6 之前这个类没有泛型。
	private JButton  b= new JButton("Add items");
	private int count = 0 ;
	
	public ComboBoxes() {
		for(int i = 0; i < 2; i++) {
			c.addItem(desc[count++]);
		}
		c.setEditable(true);                       // 可编辑
		t.setEditable(false);
		b.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				if(count < desc.length) {
					c.addItem(desc[count++]);
				}
			}
		});
		
		c.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				t.setText("index: " + c.getSelectedIndex() + "   " + ((JComboBox<?>)e.getSource()).getSelectedItem());
			}
			
		});
		
		setLayout(new FlowLayout());
		add(t);
		add(c);
		add(b);
	}
	
	public static void main(String[] args) {
		SwingConsole.run(new ComboBoxes(), 200, 175);
	}
}
